﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Activities.Rules;
using RelationExpertSystem.Controllers;
using System.Diagnostics;

namespace RelationExpertSystem
{
    class RelationSession : ISession
    {
        private PeopleController _peopleController;
        private RelationRulesManager _rulesManager;

        public event EventHandler<FactsEventArgs> FactsLoaded
        {
            add { _peopleController.FactsLoaded += value; }
            remove { _peopleController.FactsLoaded -= value; }
        }

        public event EventHandler<FactsEventArgs> FactsUpdated
        {
            add { _peopleController.FactsUpdated += value; }
            remove { _peopleController.FactsUpdated -= value; }
        }

        public event EventHandler<MessageEventArgs> NewInference;
        private void RaiseNewInference(MessageEventArgs args)
        {
            EventHandler<MessageEventArgs> eh = NewInference;
            if (eh != null)
                eh(this, args);
        }

        public RelationSession(RelationRulesManager rulesManager)
        {
            _peopleController = new PeopleController(); // TODO: decouple
            _rulesManager = rulesManager;

            _rulesManager.NewRelationInferred += new EventHandler<RelationEventArgs>(HandleNewRelationInferred);
        }

        public void LoadFacts()
        {
            _peopleController.LoadPeople();
        }

        public void EditFacts()
        {
            _peopleController.EditPeople();
        }

        public void NewFacts()
        {
            _peopleController.NewPeople();
        }

        public void Infer()
        {
            _rulesManager.FireRules<RelationEventArgs>(_peopleController.GetPairs());
        }

        public void ClearInferences()
        {
            _peopleController.ClearInferredRelations();
        }

        private void HandleNewRelationInferred(object sender, RelationEventArgs e)
        {
            string message = String.Format("{0} is {1}'s {2}", e.PersonB.Name, e.PersonA.Name, e.Relation.GetType().GetShortName());
            RaiseNewInference(new MessageEventArgs(message));
            Debug.WriteLine("Inference: " + message);
        }
    }
}
